﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.ServiceModel;
using System.Text;
using System.Xml;
using RunCamlSample.QueryBuilders;
using RunCamlSample.SharePointList;
using System.Linq;

namespace RunCamlSample
{
    class Program
    {
        static void Main(string[] args)
        {
            QueryProcceser procceser1 = new QueryProcceser("http://gnc:5555/sites/Test/_vti_bin/lists.asmx");
            QueryProcceser procceser2 = new QueryProcceser("http://gnc-tungnt9/_vti_bin/lists.asmx");

            procceser1.LoadList("Discussion");
            procceser2.LoadList("Team Discussion");

            //string id = procceser2.GetDestinationRef("6");

            //Console.WriteLine(id);

            ReturnAllField(procceser1);

            //TestAddDiscustionAndMessage(procceser2);

            //TestAddDiscustion(procceser2);

            //TestDiscussion(procceser2);

            //FolderFieldSample(procceser2);

            //CreateItemSample(procceser2);

            //ExecuteItem(procceser1);

            //ExecuteMigrateFolder(procceser1, procceser2);

            //ExecuteBatchSample(procceser1);

            //CreateFolderSample(procceser2);
            
            //QuerySample(procceser);
        }

        private static void ReturnAllField(QueryProcceser procceser2)
        {
            IList<string> list = procceser2.GetAllField();
            //list.Remove("Body");
            //list.Remove("MessageBody");
            //list.Remove("FullBody");
            //list.Remove("LimitedBody");
            //list.Remove("BodyAndMore");

            //IList<string> list = new List<string>() { "ID", "ThreadIndex", "ContentType", "Body", "MessageId", "TrimmedBody", "Body" };
            if (File.Exists("result.txt")) File.Delete("result.txt");
            TextWriter writer = new StreamWriter("result.txt");

            procceser2.ExcuteItem(list.ToArray(), 100,
                                  (r) =>
                                      {
                                          foreach (var result in r.Lists)
                                          {
                                              Console.WriteLine("--------------------------------------------------------------------------------------");
                                              writer.WriteLine("-------------------------------------------------------------------------------------");
                                              foreach (var field in list)
                                              {
                                                  Console.WriteLine(field + ": " + result[field]);
                                                  writer.WriteLine(field + ": " + result[field]);
                                              }
                                          }
                                      });
            writer.Close();
            var q = new Process();
            q.StartInfo = new ProcessStartInfo("result.txt");
            q.Start();
        }

        private static void TestAddDiscustion(QueryProcceser procceser2)
        {
            NameValueCollection values = new NameValueCollection();
            
            values["Message-ID"] = "99";
            values["Thread-Index"] = Base64Encoder.Encode("" + Guid.NewGuid() + "@test");
            values["Subject"] = "This is the topic";
            values["Mime-Version"] = "1.0";
            values["Content-type"] = "text/plain; charset=us-ascii";
            procceser2.AddDiscussionBoardItem(values, "This is body of topic");
        }

        private static void TestAddDiscustionAndMessage(QueryProcceser procceser2)
        {
            BatchQueryBuilder query = new BatchQueryBuilder();
            query.RootFolder("/Lists/Team Discussion");
            query.Method("1", Command.New).Fields(new List<FieldEx>
                                                         {
                                                             new FieldEx { Name = "Title", Value = "Add Discustion" },
                                                             new FieldEx { Name = "BaseName", Value = "Add Discustion" },
                                                             new FieldEx { Name = "Body", Value = "Add Discustion Body" },
                                                             new FieldEx { Name = "ThreadIndex", Value = "0x01CE2EC3B4FD3F0A91F79A314A2F98A2EB085D438EB5" },
                                                             new FieldEx { Name = "MessageId", Value = "<" + Guid.NewGuid().ToString("N").ToLower() + "@SharePoint>"},
                                                             new FieldEx { Name = "ContentType", Value = "Discussion" },
                                                             new FieldEx { Name = "IsRootPost", Value = "1" },
                                                             new FieldEx { Name = "FSObjType", Value = "1" },
                                                         });

            query.OnError(OnErrorType.Return);

            //procceser2.UpdateListItem(query);

            BatchQueryBuilder query2 = new BatchQueryBuilder();
            query2.RootFolder("/Lists/Team Discussion/Add Discustion");
            query2.Method("1", Command.New).Fields(new List<FieldEx>
                                                         {
                                                             new FieldEx { Name = "Body", Value = "Add Reply Body" },
                                                             new FieldEx { Name = "ThreadIndex", Value = "0x01CE2EC3B4FD3F0A91F79A314A2F98A2EB085D438EB5002F734D2F" },
                                                             new FieldEx { Name = "MessageId", Value = "<" + Guid.NewGuid().ToString("N").ToLower() + "@SharePoint>"},
                                                             new FieldEx { Name = "ContentType", Value = "Message" },
                                                             new FieldEx { Name = "IsRootPost", Value = "0" },
                                                             new FieldEx { Name = "ParentFolderId", Value = "86" },
                                                             new FieldEx { Name = "FSObjType", Value = "0" },
                                                         });

            query2.OnError(OnErrorType.Return);

            //procceser2.UpdateListItem(query2);

            //procceser2.DeleteItems("87");
            
            ReturnAllField(procceser2);
        }

        private static void TestDiscussion(QueryProcceser procceser2)
        {
            var fields = new[]
                             {
                                 "ID",
                                 "LinkDiscussionTitle",
                                 "Title", "IsRootPost", "ShortestThreadIndexIdLookup", 
                                 "ParentFolderId", "ThreadIndex",
                                 "BaseName",                                 
                                 "SyncClientId"
                             };

            procceser2.ExcuteItem(fields, 100,
                                  (r) =>
                                      {
                                          foreach (var result in r.Lists)
                                          {
                                              Console.WriteLine("------------------");
                                              foreach (var field in fields)
                                              {
                                                  Console.WriteLine(field + ": " + result[field]);
                                              }
                                          }
                                      });


            Console.WriteLine("Add Reply");

            BatchQueryBuilder query = new BatchQueryBuilder();
            query.RootFolder("/Lists/Team Discussion");
            query.Method("1", Command.New).Fields(new List<FieldEx>
                                                         {
                                                             new FieldEx { Name = "Title", Value = "Auto Discusstion 5"
                                                                 },
                                                             new FieldEx
                                                                 {Name = "BaseName", Value = "Auto Discusstion 5"},
                                                             new FieldEx {Name = "Title", Value = "Auto Discusstion 5"},
                                                             new FieldEx {Name = "Body", Value = "Auto Discusstion 5"},
                                                             new FieldEx
                                                                 {
                                                                     Name = "ThreadIndex",
                                                                     Value =
                                                                         "0x01CE2EC3B4FD3F0A91F79A314A2F98A2EB085D438EB300024C8C36"
                                                                 },
                                                             //new FieldEx { Name = "ContentType", Value = "Discussion" },
                                                             new FieldEx {Name = "MyCustomField", Value = "CustomField"},
                                                             //new FieldEx { Name = "FSObjType", Value = "1" },
                                                         });

            query.OnError(OnErrorType.Return);

            procceser2.UpdateListItem(query);
        }

        private static void FolderFieldSample(QueryProcceser procceser2)
        {
            var fields = new[]
                             {
                                 "GUID", "Title", "ContentType", "BaseName", "EncodedAbsUrl", "FileDirRef",
                                 "Author", "Created", "Editor",  "Modified", "ID"
                             };

            procceser2.ExcuteFolder(fields, 1,
                                    (r) =>
                                        {
                                            foreach (var result in r.Lists)
                                            {
                                                foreach (var field in fields)
                                                {
                                                    Console.WriteLine(field + ": " + result[field]);
                                                }
                                            }
                                        });
        }

        private static void CreateItemSample(QueryProcceser procceser2)
        {
            BatchQueryBuilder query = new BatchQueryBuilder()
                            .OnError(OnErrorType.Return)
                            .Method("1", Command.Update)
                            .Fields(new List<FieldEx>
                                        {
                                            new FieldEx { Name = "ID", Value = "256" },
                                            new FieldEx { Name = "Title", Value = "Item6" }
                                        });

            procceser2.UpdateListItem(query);
        }

        private static void ExecuteItem(QueryProcceser procceser1)
        {
            procceser1.ExcuteItem(new[] { "GUID", "Title", "ContentType", "BaseName", "Modified", "EncodedAbsUrl", "FileDirRef" }, 100,
                (r) => 
            {
                foreach (var result in r.Lists)
                {
                    Console.WriteLine(result.Id + ": " + result["Title"] + ": " + result["BaseName"] + " Path:" + result.BasePath);
                }
            });
        }

        private static void ExecuteMigrateFolder(QueryProcceser procceser1, QueryProcceser procceser2)
        {
            Console.WriteLine(procceser1.GetRootPath());
            Console.WriteLine(procceser2.GetRootPath());

            procceser1.ExcuteFolder(
                new[] {"GUID", "Title", "ContentType", "BaseName", "Modified", "EncodedAbsUrl", "FileDirRef" }, 100,
                (r) =>
                    {
                        procceser2.CreateFolder(
                            r.Lists.Select(c => procceser1.GetLocalPath(c.BasePath) + "/" + c.BaseName).ToList());
                    });
        }

        private static void CreateFolderSample(QueryProcceser procceser)
        {
            procceser.CreateFolder(new List<string>() { "Test/Test7" });
        }

        private static void ExecuteBatchSample(QueryProcceser procceser)
        {
            Console.WriteLine(procceser.GetRootPath());
            procceser.ExcuteFolder(new[] { "GUID", "ContentType", "BaseName", "Modified", "EncodedAbsUrl", "FileDirRef", "MyDate", "Title" }, 100,
                                  (r) =>
                                      {
                                          foreach(var result in r.Lists)
                                          {
                                              Console.WriteLine(result.Id + ": " + result["Title"] + ": " + result["BaseName"] + " Path:" + result.BasePath);
                                          }
                                      });
        }

        private static void QuerySample(QueryProcceser procceser)
        {
            var query = new QueryBuilder()
                .And()
                    .Where("Title", QueryOperation.Contains, "Folder", "Text")
                    .Where("ID", QueryOperation.Eq, "13", "Counter")
                .EndAnd()
                .OrderBy("ID", true);

            //var options = new QueryOptionsBuilder()
            //    .Folder("Sub Folder 1.2")
            //    .MandatoryColumns(true)
            //    .Scope(Scope.All);
            QueryOptionsBuilder options = null;

            ViewBuilder viewBuilder = new ViewBuilder().AppendField(new[] { "GUID", "ContentType", "BaseName", "Modified", "EncodedAbsUrl", "MyDate" });

            //procceser.CreateFolder(new List<string>() { "Auto Folder", "Auto Folder 2" }, "/sites/Test/Lists/Source Custom List/Auto Folder");
            //procceser.CreateFolder(new List<string>() { "Auto Folder", "Auto Folder 2" }, "/Lists/Test_Tool");
            //Console.WriteLine(procceser.GetRootPath());

            ResultList rows = procceser.GetListItems(query, viewBuilder, options, null);

            foreach (Result row in rows.Lists)
            {
                Console.WriteLine(row["ID"] + ": " +  row["Title"]);
            }
        }
    }
}

